package com.kky.pp.activity.login

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.core.view.isVisible
import com.appsflyer.AppsFlyerLib
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.manager.SDActivityManager
import com.custom.base.mvp.BasePresenterImpl
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.kky.pp.common.Constant
import com.kky.pp.R
import com.kky.pp.entity.AgreementEntity
import com.kky.pp.entity.IMTokenGetEntity
import com.kky.pp.entity.LoginParamEntity
import com.kky.pp.http.CommonHttpResutHead
import com.kky.pp.rongyun.RongConfigUtil
import com.kky.pp.activity.login.helper.LoginRegisterHelper
import io.rong.imkit.SpName
import io.rong.imkit.activity.RongWebviewActivity


/**
 * 作者：
 * 时间：
 * 描述：登录
 */
class LoginPresenter : BasePresenterImpl<LoginContract.View>(), LoginContract.Presenter {

    val loginRegisterHelper by lazy { LoginRegisterHelper() }
    override fun initBundle(bundle: Bundle) {
        mView?.apply {
            BaseConfig.getInstance.addHead("basicParams", CommonHttpResutHead.getHead().toString())
            val loginWay = bundle.getString("loginWay") ?: ""
            txtDLPhones.visibility = if (loginWay.contains("phone")) View.VISIBLE else View.GONE
            val animationEnlarge: Animation =
                AnimationUtils.loadAnimation(mActivity, R.anim.anim_transfer_1000)
            conDLContainers.startAnimation(animationEnlarge)
            if (!SDActivityManager.instance.isEmpty) {
                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.user_config_url)
                        requestBody.add("code", 2)
                        AppsFlyerLib.getInstance().getAppsFlyerUID(mActivity)
                            ?.let { requestBody.add("appsFlyerUid", it) }
                        requestBody.add(
                            "channel",
                            BaseConfig.getInstance.getString(SpName.channel, "")
                        )
                    }
                }, object : SDOkHttpResoutCallBack<AgreementEntity>() {
                    override fun onSuccess(entity: AgreementEntity) {
                        val style = SpannableStringBuilder()
                        style.append(mActivity.getString(R.string.login_protocol))

                        style.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(p0: View) {
                                    val b = Bundle()
                                    b.putString("url", entity.data.terms)
                                    b.putString(
                                        "title",
                                        mActivity.resources.getString(R.string.user_agreement)
                                    )
                                    startActivity(RongWebviewActivity::class.java, b)
                                }

                                override fun updateDrawState(ds: TextPaint) {
                                    ds.flags = TextPaint.FAKE_BOLD_TEXT_FLAG
                                    ds.isUnderlineText = true
                                    ds.color = Color.WHITE
                                    ds.clearShadowLayer()
                                }
                            },
                            style.indexOf("Terms"),
                            style.indexOf("Terms") + 5,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )

                        style.setSpan(
                            object : ClickableSpan() {
                                override fun onClick(p0: View) {
                                    val b = Bundle()
                                    b.putString("url",entity.data.privacyPolicy)
                                    b.putString(
                                        "title",
                                        mActivity.resources.getString(R.string.privacy_items)
                                    )
                                    startActivity(RongWebviewActivity::class.java, b)
                                }

                                override fun updateDrawState(ds: TextPaint) {
                                    ds.flags = TextPaint.FAKE_BOLD_TEXT_FLAG
                                    ds.isUnderlineText = true
                                    ds.color = Color.WHITE
                                    ds.clearShadowLayer()
                                }
                            },
                            style.indexOf("&") + 2,
                            style.length,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )

                        txtDLProtocols.text = style
                        txtDLProtocols.movementMethod = LinkMovementMethod.getInstance()
                    }
                })
            }
            val source = bundle.getBoolean("isDeleteAccount")
            val recallContent = BaseConfig.getInstance.getString(SpName.recallLogingHintContent, "")
            if (source && recallContent.isNotEmpty()) {
                frameDLRecallHints.isVisible = source
                tvDLRecallContents.text = recallContent
                Handler().postDelayed(Runnable {
                    frameDLRecallHints.isVisible = false
                }, 6000)
            }
            loginRegisterHelper.requestRegisterConfig()
        }
    }
    fun getLoginToken(user: GoogleSignInAccount, type: String) {
        OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
            override fun addBody(requestBody: OkHttpBodyEntity) {
                requestBody.setPost(Constant.login_Url)
                user.account?.name?.let { requestBody.add("account", it) }
                user.email?.let { requestBody.add("email", it) }
                requestBody.add("loginType", type)
                user.displayName?.let { requestBody.add("userName", it) }
            }
        }, object : SDOkHttpResoutCallBack<LoginParamEntity>() {
            override fun onSuccess(entity: LoginParamEntity) {
                BaseConfig.getInstance.addHead(
                    "basicParams",
                    CommonHttpResutHead.getHead(entity.data.token).toString()
                )
                BaseConfig.getInstance.setString(SpName.token, entity.data.token)
                BaseConfig.getInstance.setString(SpName.userCode, entity.data.userCode)
                if (entity.data.nickName != null) {
                    BaseConfig.getInstance.setString(SpName.nickName, entity.data.nickName)
                }
                if (entity.data.avatarUrl != null) {
                    BaseConfig.getInstance.setString(SpName.avatarUrl, entity.data.avatarUrl)
                }
                BaseConfig.getInstance.setBoolean(SpName.profileComplete, entity.data.isUserValid)
                if (entity.data.isUserValid) {
                    OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                        override fun addBody(requestBody: OkHttpBodyEntity) {
                            requestBody.setPost(Constant.im_token_Url)
                        }
                    }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                        override fun onSuccess(parms: IMTokenGetEntity) {
                            RongConfigUtil.connectIMLogin(
                                parms.data.token,
                                entity.data.userCode,
                                entity.data.nickName,
                                entity.data.avatarUrl ?: ""
                            )
                        }

                        override fun onFailure(code: Int, msg: String) {
                        }
                    })
                } else {
                    loginRegisterHelper.upAddProfile(mActivity)
                }
            }

            override fun onFailure(code: Int, msg: String) {
                mView?.apply {
                    lottieDLLoadings.visibility = View.GONE
                    lottieDLLoadings.pauseAnimation()
                }
            }

            override fun onFinish() {
                user.idToken?.let { BaseConfig.getInstance.setString(SpName.googleToken, it) }
            }
        })
    }

}